﻿using Mysoft.Common.Const;
using Mysoft.Common.Exceptions;
using Mysoft.Common.Extensions;
using Mysoft.Common.Model;
using Mysoft.Data.CacheManager.IService;
using Mysoft.Entity;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Mysoft.Data.UserManager
{
    public class UserContext
    {
      

        /// <summary>
        /// 为了尽量减少redis或Memory读取,保证执行效率,将UserContext注入到DI，
        /// 每个UserContext的属性至多读取一次redis或Memory缓存从而提高查询效率
        /// </summary>
        public static UserContext Current
        {
            get
            {
                return GetService<UserContext>();
            }
        }

        /// <summary>
        /// 缓存服务
        /// </summary>
        private static ICacheService _CacheContext
        {
            get { return GetService<ICacheService>(); }
        }

        /// <summary>
        /// 用户实体服务
        /// </summary>
        private static EntityService<Sys_User> UserEntityService 
        {
            get { return GetService<EntityService<Sys_User>>(); }
        }

        /// <summary>
        /// 获取服务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        private static T GetService<T>() where T : class
        {
            return HttpContext.Current.RequestServices.GetService(typeof(T)) as T;
        }

        public UserInfo UserInfo
        {
            get
            {
                //if (_userInfo != null && _userInfo.Id.HasValue)
                //{
                //    return _userInfo;
                //}
                lock (_Lock)
                {
                    return GetUserInfo(UserId);
                }
            }
        }

        private UserInfo? _userInfo { get; set; }

        ///// <summary>
        ///// 角色ID为1的默认为超级管理员
        ///// </summary>
        //public bool IsSuperAdmin
        //{
        //    get { return IsRoleIdSuperAdmin(this.RoleId); }
        //}
        ///// <summary>
        ///// 角色ID为1的默认为超级管理员
        ///// </summary>
        //public static bool IsRoleIdSuperAdmin(int roleId)
        //{
        //    return roleId == 1;
        //}

        private UserInfo GetUserInfo(Guid? userId)
        {
            //if (_userInfo != null && _userInfo.Id.HasValue && userId.Equals(_userInfo.Id)) return _userInfo;
            //if (!userId.HasValue)
            //{
            //    _userInfo = new UserInfo();
            //    return _userInfo;
            //}
            string key = userId.GetUserKey();
            _userInfo = _CacheContext.Get<UserInfo>(key);
            if (_userInfo != null && _userInfo.Id.HasValue) return _userInfo;

            _userInfo = UserEntityService.Instance
                .Find(x => x.Id == userId).Select(s => new UserInfo()
                {
                    Id = userId.Value,
                    Name = s.Name,
                    Code = s.Code,
                    Token = s.Token      
                }).FirstOrDefault();

            if (_userInfo != null && _userInfo.Id.HasValue)
            {
                _CacheContext.AddObject(key, _userInfo);
            }
            return _userInfo ?? new UserInfo();
        }

        public Guid? UserId
        {
            get
            {
                var v = (HttpContext.Current.User.FindFirst(JwtRegisteredClaimNames.Jti)
                    ?? HttpContext.Current.User.FindFirst(ClaimTypes.NameIdentifier));
                return v != null ? v.GetGuid().Value : null;
            }
        }
        public void LogOut(Guid userId) 
        {
            string key = userId.GetUserKey();
            _CacheContext.Remove(key);
        }

        /// <summary>
        /// 锁
        /// </summary>
        private readonly object _Lock = new object();
    }
}
